import { Outlet, RouteObject } from 'react-router-dom'
import React from 'react'
import { RoutesToModules } from '@/router'

const keys = Object.keys(RoutesToModules)

// 最后一步：将配置项映射出组件，因为组件只能在最后一步做，在前面做的话存起来再取出去也许不是一个组件了
export function addModuleToRoute(routes: RouteObject[]): RouteObject[] {
  const newRoutes = routes.map((item) => {
    const key = keys.find((key) => item.path === key)
    //   path: '/main/system/log',
    //   element: <Outlet />,
    //   children: [
    //     {
    //       path: '/main/system/log',
    //       element: <Navigate to="/main/system/log/login" />
    //     },
    // 下面第一个if语句就是为了生成上面的目标
    if (item.children && item.children.length) {
      item.element = <Outlet />
      if (key) {
        const firstChild = { path: item.path, element: RoutesToModules[key] }
        item.children.unshift(firstChild)
      }
      addModuleToRoute(item.children)
    } else {
      // 正常生成
      if (key) item.element = RoutesToModules[key]
    }
    return item
  })
  return newRoutes
}

// 映射出来配置项，有path但还没有element组件
export function mapMenusToRoutes(
  menuList: any,
  routes: RouteObject[]
): RouteObject[] {
  const arr: RouteObject[] = []
  menuList.forEach((item: any) => {
    // 嵌套路由
    if (item.children && item.children.length) {
      const children: RouteObject[] = []
      children.push(...mapMenusToRoutes(item.children, routes))
      const routeConfig: RouteObject = {
        path: '/main' + item.path,
        children
      }
      arr.push(routeConfig)
    } else {
      // 单个路由
      const result = routes.find(
        (iitem) => iitem.path?.split('/main')[1] === item.path
      )
      result && arr.push(result)
    }
  })
  return arr
}
